package com.group.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.group.domain.Comment;
import com.group.domain.Media;
import com.group.dao.CommentDao;
import com.group.dao.UserDao;
import com.group.domain.User;
import com.sun.org.apache.bcel.internal.generic.NEW;


/**
 * 用户控制类
 * 
 * @author zs，zst
 * @version 1.0
 */
@Controller
@SessionAttributes({ "user" })
public class UserController {

	/**	评论信息数据表接口	**/
	CommentDao commentDao = new CommentDao();
	/**	用户信息数据表接口	**/
	UserDao userDao = new UserDao();
	
	/**
	 * 用户评论界面
	 * @param map
	 * @param model
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("user/mycomment")
	public String commentList(ModelMap map, Model model, @RequestParam(defaultValue = "1") int page, HttpSession session) {
		long count = commentDao.countByUser((User)model.asMap().get("user"));
		map.addAttribute("page", page);
		List<Comment> commentList = commentDao.findCommentListByPage(page, 8,(User) session.getAttribute("user"));
		model.addAttribute("pageCount", Math.ceil(count / 8.0));
		model.addAttribute("commentList", commentList);
		return "home/mycomment";
	}
	
	/**
	 * 用户登录检测
	 * @param request
	 * @param response
	 * @param username
	 * @param password
	 * @param model
	 * @param rememberMe
	 * @return
	 */
	@RequestMapping(value = "/checkUser", method = RequestMethod.POST)
	public String checkUser(HttpServletRequest request, HttpServletResponse response,
												@RequestParam(value = "loginUsername") String username,
												 @RequestParam(value = "loginPassword") String password,Model model,
												 @RequestParam(value= "rememberme", defaultValue = "false") boolean rememberMe) {
		if (userDao.findOneByName(username) == null) {
			model.addAttribute("loginmessage", false);
			return "home/user";
		}else {
		    User user = null;
			if ((user = userDao.checkPassword(username, password)) != null) {//验证密码
				request.getSession().setAttribute("loggedInUser", user);
				// 验证成功，设置Cookie
		        if (rememberMe) {
		            Cookie cookie = new Cookie("rememberUsername", username);
		            cookie.setMaxAge(30 * 24 * 60 * 60); // 设置过期时间为30天
		            response.addCookie(cookie);
		            Cookie pcookie = new Cookie("rememberPassword", password);
		            cookie.setMaxAge(30 * 24 * 60 * 60); // 设置过期时间为30天
		            response.addCookie(pcookie);
		        } else {
		            // 不记住用户名，删除Cookie
		            Cookie cookie = new Cookie("rememberUsername", null);
		            cookie.setMaxAge(0); // 设置过期时间为0秒
		            response.addCookie(cookie);
		            Cookie pcookie = new Cookie("rememberPassword", null);
		            pcookie.setMaxAge(0); // 设置过期时间为0秒
		            response.addCookie(pcookie);
		        }
				if(user.getRole()) {
					// 管理员
					model.addAttribute("user", user);
					return "redirect:manager/home";
				}
				model.addAttribute("user", user);
				return "redirect:userInfo";
			} else {
				model.addAttribute("loginmessage", false);
				return "home/user";
			}
		}
	}
	
	/**
	 * 用户注册检测
	 * @param username	用户名
	 * @param password	密码
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/addUser", method = RequestMethod.POST)
	public String addUser(@RequestParam(value = "registerUsername") String username,
												 @RequestParam(value = "registerPassword") String password,Model model) {
		if (userDao.findOneByName(username) != null) {
			model.addAttribute("message", false);
			return "home/user";
		} else {
		    User user = new User();
		    user.setUsername(username);
		    user.setPassword(password);
		    user.setEmail("");
		    user.setIsDelete(false);
		    user.setPhone("");
		    user.setDescription("");
		    user.setRegistrationDate(new Date());
		    user.setRole(false);
			if (userDao.saveUser(user)) {
				model.addAttribute("message", true);
				return "home/user";
			} else {
				return "home/user";
			}
		}
	}
	
	/**
	 * 用户信息修改
	 * @param username	用户名
	 * @param email			email
	 * @param phoneNo		电话
	 * @param description	签名
	 * @param password	密码
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/edit", method=RequestMethod.POST)
	public String updateUser(@RequestParam(value="editUsername") String username,
							 @RequestParam(value="editEmail") String email,
							 @RequestParam(value="editPhoneNo") String phoneNo,
							 @RequestParam(value="editDescription") String description,
							 @RequestParam(value="editPassword") String password, Model model) {
		if(userDao.findOneByName(username) == null) {
			return "redirect:userInfo";
		}else {
			User user =userDao.findOneByName(username);
			user.setEmail(email);
			user.setPhone(phoneNo);
			user.setDescription(description);
			user.setPassword(password);
			userDao.update(user);
			model.addAttribute(user);
			return "home/userInfo";
		}
	}
	
	/**
	 * 用户退出登录
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/exit")
	public String backToLogin(Model model, HttpSession session) {
		model.asMap().clear();
		session.removeAttribute("user");
		return "redirect:user";
	}
	
	/**
	 * 登录注册界面
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/user")
	public String showUser(HttpSession session, Model model) {
		if (!model.containsAttribute("user")) {
			return "home/user";
		} else {
			return "home/userInfo";
		}
	}

	/**
	 * 用户信息界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/userInfo")
	public String showRegister(Model model) {
		return "home/userInfo";
	}
	
	/**
	 * 删除评论
	 * 
	 * @param model
	 * @param id    评论id
	 * @return
	 */
	@RequestMapping(value = "/deleteComment", method = RequestMethod.POST)
	public String deleteComment(Model model, @RequestParam(value = "commentId") String id) {
		boolean flag = commentDao.delete(Integer.parseInt(id));
		model.addAttribute("deleted", flag);
		return "redirect:user/mycomment";
	}
	
	/**
	 * 修改评论
	 * @param model
	 * @param id						评论id
	 * @param newcomment	修改后的评论内容
	 * @param rating				修改后的评论评分
	 * @return
	 */
	@RequestMapping(value = "/editComment", method = RequestMethod.POST)
	public String editComment(Model model, @RequestParam(value = "commentId") String id,
											@RequestParam(value = "newComment") String newcomment,
											@RequestParam(value = "rating") int rating) {
		Comment comment = commentDao.findOneById(Integer.parseInt(id));
		comment.setCommentText(newcomment);
		comment.setRating(rating);
		commentDao.update(comment);
		return "redirect:user/mycomment";
	}
}
